﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace BEELab
{
    public partial class EditInvitation : System.Web.UI.Page
    {
        /// <summary>
        /// Occures on every page load (first time or Post Back)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //If current user is not allowed to edit this invitation - reurn to Main page
            if (Request.QueryString["ID"] != null && BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetOwnerID(int.Parse(Request.QueryString["ID"].ToString())) != int.Parse(Session["UserID"].ToString()) && (Session["Admin"] == null || (bool)Session["Admin"] == false))
            {
                Response.Redirect("Main.aspx");
            }

            //If user has premmisions to edit this invitation
            if (!IsPostBack)
            {
                //If invitation exists - retrieves invitations details: Name, Code, variables etc.. to present to the user
                if (Request.QueryString["ID"] != null)
                {
                    txtName.Text = BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetName(int.Parse(Request.QueryString["ID"].ToString()));
                    txtUniqueCode.Text = BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetCode(int.Parse(Request.QueryString["ID"].ToString()));

                    FillVariables();

                    HyperLink1.NavigateUrl += BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetCode(int.Parse(Request.QueryString["ID"].ToString()));
                    HyperLink1.Text = Request.Url.OriginalString.Substring(0,Request.Url.OriginalString.IndexOf('/', 7)) + "/" + ResolveClientUrl(HyperLink1.NavigateUrl);
                }
            }
            else
            {
                //If it is a new invitation - present to the user initial invitation values
                literal1.Text = "<script>parent.$.fancybox.close(); window.parent.location.reload();    </script>";
            }
        }

        private DataTable SessionValues;
        private DataTable InvitationValues;

        /// <summary>
        /// Gets all variables and their values that belongs to this invitation's experiment, and present it to user.
        /// </summary>
        private void FillVariables()
        {
            //Gets sessionID according to invitationID 
            int SessionID = BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetSessionIDByInvitationID(int.Parse(Request.QueryString["ID"].ToString()));

            //Get ALL variables (session's and Invitaion's) of this experiment, insert in to DataTable
            SqlCommand command = new SqlCommand();
            command.CommandText = "SELECT * FROM Variables WHERE ProgramID=@ProgramID AND Scope='Subject'";
            command.Parameters.Add(new SqlParameter("@ProgramID", BEELab.Logic.ProgramManagement.SessionManagement.SessionManagement.GetProgramIDBySessionID(SessionID)));
            DataTable AllVariables = BEELab.Data.DBHelper.ExecuteQuery(command);

            //Gets first stage and insert it to AllVariables DataTable
            DataRow newRow = AllVariables.NewRow();
            newRow["ID"] = 0;
            newRow["Name"] = "First Stage";
            newRow["Scope"] = "Subject";
            newRow["DefaultValue"] = BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.GetFirstStage(int.Parse(Request.QueryString["ID"].ToString()));
            AllVariables.Rows.InsertAt(newRow, 0);

            //Fill in SessionValues DataTable with variables that belongs to session only
            command.CommandText = "SELECT VariableID, Value FROM InitialValues WHERE ParentID=@SessionID AND Type='Session'";
            command.Parameters.Add(new SqlParameter("@SessionID", SessionID));
            SessionValues = BEELab.Data.DBHelper.ExecuteQuery(command);

            //Fill in InvitationValues DataTable with variables that belongs to Invitation only
            command.CommandText = "SELECT VariableID, Value FROM InitialValues WHERE ParentID=@InvitationID AND Type='Invitation'";
            command.Parameters.Add(new SqlParameter("@InvitationID", int.Parse(Request.QueryString["ID"].ToString())));
            InvitationValues = BEELab.Data.DBHelper.ExecuteQuery(command);

            //Bind between AllVariables DataTable and the GUI
            rptSessionVariable.DataSource = AllVariables;
            rptSessionVariable.DataBind();
        }

        /// <summary>
        /// Raises an event once one of the values of the variables on the page changes by the user.
        /// Occurs after an item in the Repeater control is data-bound but before it is rendered on the page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptSessionVariable_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var item = (DataRowView)e.Item.DataItem;
            var tValue = ((TextBox)e.Item.FindControl("txtVariable"));
            var oldValue = ((Label)e.Item.FindControl("lblOldValue"));

            DataRow[] foundRows = InvitationValues.Select("VariableID=" + item["ID"].ToString());

            if (foundRows.Length > 0)
            {
                tValue.Text = foundRows[0]["Value"].ToString();
            }
            else
            {
                foundRows = SessionValues.Select("VariableID=" + item["ID"].ToString());

                if (foundRows.Length > 0)
                {
                    tValue.Text = foundRows[0]["Value"].ToString();
                }
                else
                {
                    tValue.Text = item["DefaultValue"].ToString();
                }
            }

            oldValue.Text = tValue.Text;
        }

        /// <summary>
        /// Occures once the user press on Submit button in order to save invitation new values.
        /// Updates all variables values for this specific invitation on DB.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.UpdateInvitation(int.Parse(Request.QueryString["ID"].ToString()), txtName.Text);

            foreach (RepeaterItem item in rptSessionVariable.Items)
            {
                if (((Label)item.FindControl("lblOldValue")).Text != ((TextBox)item.FindControl("txtVariable")).Text)
                {
                    BEELab.Logic.ProgramManagement.SessionManagement.InvitationManagement.SetVariableValue(int.Parse(Request.QueryString["ID"].ToString()), int.Parse(((Label)item.FindControl("lblVariableId")).Text), ((TextBox)item.FindControl("txtVariable")).Text);
                }
            }
        }

        /// <summary>
        /// Updates invitation's URL string according to user's choice. 
        /// If users choose "NO" - URL string will be shorter (withour header)
        /// If user choose "YES", URL string will contain header as well.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rblHeader_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblHeader.SelectedValue == "No")
            {
                HyperLink1.NavigateUrl += "&NoHeader=True";
                HyperLink1.Text += "&NoHeader=True";
            }
            else
            {
                HyperLink1.NavigateUrl = HyperLink1.NavigateUrl.Replace("&NoHeader=True", "");
                HyperLink1.Text = HyperLink1.Text.Replace("&NoHeader=True", "");
            }
        }
    }
}